<?php
namespace Backend\Models\Control;

use Backend\Models\Base;

class Activity extends Base
{
    public function initialize()
    {
        parent::initialize();
    }

    public function getSource()
    {
        return 'activity_config_list';
    }

    public function gets($limit, $offset)
    {
        $query = $this->select('id,title,status,weight')->from(self::class)->limit($limit, $offset);
        try {
            $result = $query->getQuery()->execute()->toArray();
            if ($result !== false && is_array($result)) {
                foreach ($result as $k => $value) {
                    $result[$k]['link'] = 'http://activity.scdscar.com/activity/index/show/' . trim($value['id']);
                }
                return $result;
            }
        } catch (\Exception $ex) {
            $this->errorLog('SELECT', $query->getPhql(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }

    public function getCount()
    {
        $query = $this->select('count(*) AS cnt')->from(self::class);
        try {
            $result = $query->getQuery()->execute()->toArray();
            if ($result !== false && is_array($result) && count($result) > 0) {
                return $result[0]['cnt'];
            }
        } catch (\Exception $ex) {
            $this->errorLog('SELECT', $query->getPhql(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }

    public function add($entity)
    {
        try {
            if ($this->db()->insertAsDict(self::getSource(), $entity)) {
                return true;
            }
        } catch (\PDOException $ex) {
            $this->errorLog('INSERT', $this->db()->getSQLStatement(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }

    public function get($id)
    {
        $id = intval($id);
        try {
            $query = 'SELECT * FROM `activity_config_list` WHERE `id`=' . $id;
            $ret   = $this->db()->query($query)->fetch();
            if ($ret !== false && is_array($ret) && count($ret) > 0) {
                return $ret;
            }
        } catch (\PDOException $ex) {
            $this->errorLog('SELECT', $this->db()->getSQLStatement(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }

    public function edit($entity)
    {
        try {
            if ($this->db()->updateAsDict(self::getSource(), $entity, sprintf('id=%d LIMIT 1', intval($entity['id'])))) {
                return true;
            }
        } catch (\PDOException $ex) {
            $this->errorLog('UPDATE', $this->db()->getSQLStatement(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }
}
